﻿using System;
using EnvDTE;
using EnvDTE80;

namespace VsTortoiseSVN.Commands
{
    public abstract class ActiveProjectBase : CommandBase
    {
        /// <summary>
        /// Gets the active project path or string.Empty.
        /// </summary>
        public string FullName
        {
            get
            {
                Project project = ActiveProject;
                if (project != null)
                    return project.LongFullName();

                return string.Empty;
            }
        }

        /// <summary>
        /// Gets the active project or null when none is available.
        /// Active project is, if an active document exists, the project that contains
        /// this active document or if no active document exists, the project selected in the solution explorer.
        /// </summary>
        protected Project ActiveProject
        {
            get
            {
                // During real-world usage, testers reported the
                // active project should actually depend on in what
                // document someone is. The project of the active
                // document is wanted, rather than the selected
                // from the solution explorer.
                if (Application.HasDocument())
                {
                    ProjectItem projectItem = Application.ActiveDocument.ProjectItem;
                    if (projectItem != null && projectItem.ContainingProject != null)
                    {
                        return projectItem.ContainingProject;
                    }
                }

                // No active document available, use the real
                // active project instead.
                Project project = Application.ActiveProject();
                return project;
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public ActiveProjectBase(DTE2 app, string id)
            : base(app, id)
        {
        }
    }
}
